package com.wangbo.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class JDKProxy<T> implements InvocationHandler {
    private T targetObj; // 被代理的对象

    public T createProxy(T targetObj) {
        this.targetObj = targetObj;
        return (T) Proxy.newProxyInstance(targetObj.getClass().getClassLoader(),
                targetObj.getClass().getInterfaces(), this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object result = method.invoke(targetObj, args);// 借助反射调用被代理对象方法
// 添加用户时模拟增强
        if ("addUser".equals(method.getName())) {
            mockEnhance();
        }
        return result;
    }

    /**
     * 模拟增强
     */
    private void mockEnhance() {
        System.out.println("~~~模拟增强~~~");
    }
}
